import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpServerScoket {
	private ServerSocket serverSocket=null;
	public TcpServerScoket(int port) throws IOException {
		serverSocket=new ServerSocket(port);
	}
	public void start() throws IOException {
		System.out.println("服务器启动");
		ExecutorService threadPool=Executors.newCachedThreadPool();
		//直接创建一个线程池

		//下面就开始建立链接
		while(true) {
			Socket socketCilent=serverSocket.accept();
			threadPool.submit(new Runnable() {
				@Override
				public void run() {
					try {
						processConnection(socketCilent);
					} catch (IOException e) {
						throw new RuntimeException(e);
					}
				}
			});
		}
	}

	private void processConnection(Socket socketCilent) throws IOException {
		//当程序来到这里的时候，代表客户端已经上线了
		System.out.printf("[%s:%d] 客户端上线!\n", socketCilent.getInetAddress(), socketCilent.getPort());
		//处理数据，肯定是多条数据的
		try(InputStream inputStream=socketCilent.getInputStream();
			OutputStream outputStream=socketCilent.getOutputStream()) {
			while(true) {
				Scanner scanner=new Scanner(inputStream);
				if(!scanner.hasNext()) {
					System.out.printf("[%s:%d] 客户端下线!\n", socketCilent.getInetAddress(), socketCilent.getPort());
					break;
				}
				//1.接下里就是读取请求
				String request=scanner.next();
				//2.读取完请求之后，就是计算响应
				String response=process(request);
				//3.响应来了之后，把响应写入到流对象中
				PrintWriter printWriter=new PrintWriter(outputStream);
				//写入到这个的流对象中，自然就发送给对方了
				printWriter.println(response);
				printWriter.flush();
				System.out.printf("[%s:%d] req=%s, resp=%s\n", socketCilent.getInetAddress(), socketCilent.getPort(),
						request, response);
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
			//最后这里要关闭文件，避免资源泄露
			socketCilent.close();
		}
	}
	public String process(String request) {
		return request;
	}

	public static void main(String[] args) throws IOException {
		TcpServerScoket tcpServerScoket=new TcpServerScoket(9090);
		tcpServerScoket.start();
	}
}
